package util.core;

import java.util.ArrayList;

public class Format {

    public static String addSub(String c) {
        String representation = "";
        boolean isSub = false, isSup = false;
        for (int i = 0; i < c.length(); i++) {
            char k = c.charAt(i);
            if (isNumber(k) && !isSup) {
                if (!isSub)
                    representation += "<sub><small>";
                representation += k;
                isSub = true;
            } else {
                if (isSub) {
                    representation += "</small></sub>";
                    isSub = false;
                }
                representation += k;
            }
        }
        if (isSub)
            representation += "</small></sub>";
        return representation;
    }

    public static String toFormattedString(Molecule c) {
        String modifier;
        boolean s = c.getName().equals("");
        int charge = c.getCharge();
        if (charge > 0 && !s) {
            if (charge == 1)
                modifier = "<sup><small>+</small></sup>";
            else
                modifier = "<sup><small>" + charge + "+</small></sup>";
        } else if (charge < 0 && !s)
            if (charge == -1)
                modifier = "<sup><small>-</small></sup>";
            else
                modifier = "<sup><small>" + Math.abs(charge) + "-</small></sup>";
        else if (s)
            modifier = c.toString();
        else
            modifier = "";
        return Format.addSub(c.getName()) + modifier;
    }

    public static String toFormattedString(Equation e) {
        String representation = "<html>";
        int count = 0;
        boolean isFirst = true;
        ArrayList<Molecule> left = e.getLeft();
        ArrayList<Molecule> right = e.getRight();
        int[] balanceArray = e.getBalanceArray();
        for (Molecule c : left) {
            if (!isFirst)
                representation += "+ ";
            if (balanceArray[count] != 1)
                representation += (balanceArray[count] + toFormattedString(c) + " ");
            else
                representation += (toFormattedString(c) + " ");
            isFirst = false;
            count++;
        }
        representation += "&#8594 ";
        isFirst = true;

        for (Molecule c : right) {
            if (!isFirst)
                representation += "+ ";
            if (balanceArray[count] != 1)
                representation += (balanceArray[count] + toFormattedString(c) + " ");
            else
                representation += (toFormattedString(c) + " ");
            isFirst = false;
        }
        return representation + "</html>";
    }


    private static boolean isNumber(char num) {
        return num >= 48 && num <= 57;
    }
}
